<template>
  <div>
    <button
      class="tjks"
      style="margin-bottom: 30px"
      @click="addTest('isAddTest')"
    >
      添加考试
      <i class="el-icon-circle-plus"></i>
    </button>
    <el-dialog
      v-dialogDrag
      title="添加考试"
      :visible.sync="isAddTest"
      custom-class="customWidth"
    >
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
        @submit.native.prevent
      >
        <div style="padding: 10px">
          <el-form-item label="活动名称" prop="name">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="设备种类" prop="region">
            <el-select v-model="ruleForm.region" placeholder="请选择设备种类">
              <el-option label="低压配电装置" value="0"></el-option>
              <el-option label="带电调换电实训装置" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="考试地点" prop="region2">
            <el-cascader
              ref="exroom"
              v-model="ruleForm.region2"
              width="100%"
              placeholder="试试搜索：101"
              :options="roomlist"
              filterable
              clearable
              :props="SetKesDept"
              @change="examination"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="考试批次" prop="region3">
            <el-select
              ref="exambatch"
              v-model="ruleForm.region3"
              placeholder="请选择考试批次"
              @change="examManage($event)"
            >
              <el-option
                v-for="(bcth, i) in bacth"
                :key="i"
                :label="bcth.batchName"
                :value="bcth.batchId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="考试时间" required>
            <el-col :span="7">
              <el-form-item prop="date1">
                <el-date-picker
                  v-model="ruleForm.date1"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                  :picker-options="pickerOptionsStart"
                  style="width: 100%"
                  @change="selctimes"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col class="line" :span="1"> - </el-col>
            <el-col :span="7">
              <el-form-item prop="startTime">
                <el-time-select
                  v-model="ruleForm.startTime"
                  placeholder="起始时间"
                  :picker-options="{
                    start: istartime,
                    step: '00:02',
                    end: '18:30',
                  }"
                  @change="starselect"
                ></el-time-select>
              </el-form-item>
            </el-col>
            <el-col class="line" :span="1"> - </el-col>
            <el-col :span="7">
              <el-form-item prop="endTime">
                <el-time-select
                  v-model="ruleForm.endTime"
                  placeholder="结束时间"
                  :picker-options="{
                    start: istartime,
                    step: '00:02',
                    end: isEndTime,
                    minTime: ruleForm.startTime,
                    maxTime: isEndTime,
                  }"
                  @change="endselect"
                ></el-time-select>
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <el-form-item>
                <i
                  :class="{
                    'el-icon-circle-close': !cjsuccess,
                    'el-icon-circle-check': cjsuccess,
                    colr: !cjsuccess,
                    coll: cjsuccess,
                    colh: iscj,
                  }"
                ></i>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item>
                <button class="tjks cktime" @click="seeTime">
                  查看可用时间
                  <i class="el-icon-zoom-in"></i>
                </button>
              </el-form-item>
            </el-col>
          </el-form-item>

          <el-form-item label="考试名单" prop="testPers">
            <button class="tjks" @click="electEaxmine()">
              选择
              <i class="el-icon-circle-plus"></i>
            </button>
          </el-form-item>
          <!-- <el-form-item
            label="考位分配"
            prop="testPers2"
          >
            <button
              class="tjks"
              @click="allcation"
            >
              分配
              <i class="el-icon-circle-plus"></i>
            </button>
          </el-form-item>
          <el-form-item
            label="监考老师"
            prop="region4"
          >
            <el-select
              v-model="ruleForm.region4"
              disabled
              placeholder="请选择监考老师"
            >
              <el-option
                :label="$store.state.usersId.username"
                :value="$store.state.usersId.usersid"
              ></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">
              立即创建
            </el-button>
            <el-button @click="resetForm()"> 重置 </el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-dialog>

    <!-- 人员分配 -->
    <el-dialog
      v-dialogDrag
      title="机位分配"
      :visible.sync="isAssign"
      custom-class="customWidth"
      class="assign"
    >
      <table border="0" width="100%">
        <thead>
          <tr>
            <th with="18%">实训机号</th>
            <th :class="{ born: dd == 1 }">第一批</th>
            <th v-show="dd >= 2" :class="{ born: dd == 2 }">第二批</th>
            <th v-show="dd >= 3" :class="{ born: dd == 3 }">第三批</th>
            <th v-show="dd >= 4" :class="{ born: dd == 4 }">第四批</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in cationdata" :key="index">
            <td
              v-for="(iid, ind) in item"
              :key="ind"
              class="xylist"
              :value="iid == undefined ? '' : Object.values(iid)[0]"
            >
              <!-- <span v-if="iid == Number">{{ iid }}</span> -->
              <span>
                {{
                  typeof iid == "number"
                    ? iid
                    : iid == undefined
                    ? ""
                    : Object.values(iid)[1]
                }}
              </span>

              <!--     <span
                v-if="typeof iid != 'number'"
                class="sele"
                @click.stop="selectchange($event)"
              >
                &gt;
              </span>
              <span
                v-if="iid != undefined && typeof iid != 'number'"
                class="del"
                @click.stop="dellist($event)"
              >X</span>

              <select
                v-show="selectoggle"
                id
                name
                @change="sss($event)"
              >
                <option :value="iid == undefined ? '' : Object.values(iid)[0]">
                  {{ iid == undefined ? "" : Object.values(iid)[1] }}
                </option>
                <option
                  v-for="(iif, xnum) in lista2"
                  :key="xnum"
                  :value="Object.values(iif)[0]"
                >
                  {{ Object.values(iif)[1] }}
                </option>
              </select> -->
            </td>
          </tr>
        </tbody>
      </table>
      <!--<button>顺序分配</button>-->
      <button @click="determin">确定</button>
    </el-dialog>

    <el-dialog
      v-dialogDrag
      title="学员分配"
      :visible.sync="isUers"
      custom-class="customWidth"
    >
      <!-- 人员选择弹窗 -->

      <el-transfer
        ref="targetData"
        v-model="ruleForm.testPers"
        style="text-align: left; display: inline-block"
        filterable
        :titles="['待考学员', '已选择学员']"
        :button-texts="['移除', '选定 ']"
        :data="dataUser"
        :props="{
          key: 'studentId',
          label: 'studentName',
        }"
        @change="handleChange"
        @left-check-change="leftCheckChange"
      >
        <span slot-scope="{ option }">{{ option.studentName }}</span>
        <el-button
          slot="left-footer"
          class="transfer-footer"
          style="margin-left: 50px"
          size="small"
          @click="isUers = false"
        >
          确定
        </el-button>
        <el-button
          slot="right-footer"
          class="transfer-footer"
          style="margin-left: 50px"
          size="small"
          @click="isUers = false"
        >
          确定
        </el-button>
      </el-transfer>
    </el-dialog>

    <!-- 可用时间弹窗 -->

    <el-dialog
      v-dialogDrag
      title="已有考试时间"
      :visible.sync="timeVisible"
      custom-class="customWidth"
    >
      <el-table :data="timeTable">
        <!-- <el-table-column
          property="date"
          label="日期"
          width="180"
        ></el-table-column> -->
        <el-table-column
          property="startTime"
          label="开始时间"
        ></el-table-column>
        <el-table-column property="endTime" label="结束时间"></el-table-column>
      </el-table>
    </el-dialog>

    <!-- table -->
    <h1 class="kstable">考试列表</h1>
    <v-table ref="childquery" exam-type="1"></v-table>
  </div>
</template>
<script>
import {
  examManage,
  addnation,
  getBatch,
  quSelecteq,
  queryRoom,
  querytreeFloor,
  timejudeg,
  queryTime,
} from "@/api";
import VTable from "@/components/table";
export default {
  name: "Exama",
  components: {
    VTable,
  },
  data() {
    return {
      isAddTest: false,
      isUers: false,
      isAssign: false,
      timeVisible: false,
      cjsuccess: "", // 创建考试时间成功状态
      iscj: true,
      acalist: [], // 待分配的数据
      origindata: [], // 请求原始数据
      lista2: [], // 删除的人员
      dd: "", //分多少批次考试
      selectoggle: false, // 人员选择下拉显示
      tableData: [],
      selectRoom: [], // 班级房间列表
      subArrayNum: [],
      examAmount: 0, //设备个数
      timeTable: [], // 已有考试时间
      classroom: "", //选择班级
      SetKesDept: {
        value: "id",
        label: "title",
      },
      defaultProps: {
        //
        children: "children",
        label: "label",
      },
      roomlist: [], // 教室班级列表
      pickerOptionsStart: {
        disabledDate(time) {
          return (
            time.getTime() <
              new Date(new Date().toLocaleDateString()).getTime() ||
            time.getTime() >
              new Date(
                new Date(
                  Date.now() + 7 * 24 * 60 * 60 * 1000
                ).toLocaleDateString()
              ).getTime()
          );
        },
      },
      timeJudeg: function () {
        timejudeg({
          roomId: this.ruleForm.region2[1],
          dataTime: this.ruleForm.date1,
          startTime: this.ruleForm.startTime,
          endTime: this.ruleForm.endTime,
        })
          .then((res) => {
            console.log(res);
            if (res.result_code == 500) {
              this.$message.error("选择时间已经有考试了!");
              this.iscj = false;
              this.cjsuccess = false;
              this.ruleForm.startTime = "";
              this.ruleForm.endTime = "";
            } else {
              this.iscj = false;
              this.cjsuccess = true;
            }
          })
          .catch((err) => {
            console.log(err);
          });
      },
      istartime: "08:30",
      isEndTime: "18:31",
      ruleForm: {
        name: "",
        region: "",
        region2: "",
        region3: "",
        date1: "",
        startTime: "",
        endTime: "",
        testPers: [], // 选择的考试人员
        testPers2: [], // 分配人员
      },
      rules: {
        name: [
          { required: true, message: "请输入名称", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
        region: [
          { required: true, message: "请选择设备种类", trigger: "change" },
        ],
        region2: [
          {
            type: "array",
            required: true,
            message: "请选择考试地点",
            trigger: "blur",
          },
        ],
        region3: [
          { required: true, message: "请选择考试批次", trigger: "change" },
        ],

        date1: [
          {
            required: true,
            message: "请选择日期",
            trigger: "change",
          },
        ],
        startTime: [
          {
            required: true,
            message: "请选择开始时间",
            trigger: "change",
          },
        ],
        endTime: [
          {
            required: true,
            message: "请选择结束时间",
            trigger: "change",
          },
        ],
        testPers: [
          {
            type: "array",
            required: true,
            message: "请至少选择一名考试人员",
          },
        ],
        testPers2: [
          {
            type: "array",
            required: true,
            message: "请进行考试位分配",
          },
        ],
      },
      dataUser: [],
      value: [],
      bacth: [], // 班次信息
      devitocal: 12, // 考试设备数
      cationdata: [], // 分配后数组
      // renderFunc(h, option) {
      //   return (
      //     <span>
      //       {option.key} - {option.label}
      //     </span>
      //   );
      // },

      //二维数组创建method
      twoarrymethod: function () {
        this.acalist = [];
        let num = this.subArrayNum.length;
        let allcationUser = this.ruleForm.testPers;
        var dataArr = new Array();
        var dd = Math.ceil(allcationUser.length / num); // 算出可以分几批次考试
        this.dd = dd;
        for (let i = 0; i < allcationUser.length; i++) {
          // dataArr[parseInt(i / subArrayNum)][i % subArrayNum] = allcationUser[i];
          var aa = this.origindata.filter((item) => {
            return item.studentId == allcationUser[i];
          });
          this.acalist.push(aa[0]); // 将key 转为原始的值
        }

        for (let i = 0; i < num; i++) {
          dataArr[i] = new Array();
          for (let j = 0; j < dd; j++) {
            // dataArr[i][j] = "";
          }
        }
        for (let i = 0; i < num; i++) {
          dataArr[i][0] = this.subArrayNum[i];
          for (let j = 1; j < dd; j++) {
            dataArr[i][j] = this.acalist[i];
          }
        }
        for (let i = 0; i < num; i++) {
          dataArr[i][dd] = this.acalist[num * (dd - 1) + i];
        }
        this.cationdata = dataArr;
        this.ruleForm.testPers2 = dataArr;
      },

      resetForm() {
        this.$refs["ruleForm"].resetFields();
      },
    };
  },
  mounted() {
    getBatch().then((res) => {
      //考试批次获取
      this.bacth = res.data;
    });
    queryRoom().then((res) => {
      // 教师房间列表获取
      this.selectRoom = res.data;
    });
    querytreeFloor().then((res) => {
      // 考试地点教室获取
      this.roomlist = res.data;
    });
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.twoarrymethod();
          if (
            new Date(`${this.ruleForm.date1} ${this.ruleForm.startTime}`) <
            new Date()
          ) {
            this.$message.warning("开始时间已过,请重新选择!");
            this.ruleForm.startTime = "";
            this.ruleForm.endTime = "";
          } else {
            addnation({
              dataTime: this.ruleForm.date1,
              examinationName: this.ruleForm.name,
              equipmentType: this.ruleForm.region,
              roomId: this.ruleForm.region2[1],
              startTime: this.ruleForm.startTime,
              endTime: this.ruleForm.endTime,
              usersId: this.$store.state.users.usersId,
              student: this.ruleForm.testPers,
              batchId: this.ruleForm.region3,
              candidateSeat: this.ruleForm.testPers2,
              examType: 1,
            })
              .then((res) => {
                if (res.result_code == 200) {
                  this.$message({
                    message: "创建成功!!",
                    type: "success",
                  });
                  this.$refs.childquery.querySeinfor();
                  this.isAddTest = false;
                  this.resetForm();
                }
                if (res.result_code == 500) {
                  this.$message.error("数据非法,请重新填写!");
                  this.ruleForm.startTime = "";
                  this.ruleForm.endTime = "";
                }
              })
              .catch((error) => {
                console.log(error);
                this.$message({
                  message: "网络错误,创建失败!",
                  type: "warning",
                });
                this.isAddTest = true;
              });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 设置时间 当前天考试时间
    selctimes(val) {
      if (val) {
        this.ruleForm.startTime = "";
        this.ruleForm.endTime = "";
        let blotime = new Date(val) > new Date();
        if (!blotime) {
          let hout = new Date().getHours();
          console.log(hout);
          let mint = new Date().getMinutes();
          if (hout >= 18) {
            this.$message.error("今天已经很晚了,添加明天的考试吧!");
          }
          // let minDate = "";
          // switch (true) {
          //   case mint < 15:
          //     minDate = "15";
          //     break;
          //   case mint < 30 && mint >= 15:
          //     minDate = "30";
          //     break;
          //   case mint < 45 && mint >= 30:
          //     minDate = "45";
          //     break;
          //   case mint < 59 && mint >= 45:
          //     minDate = "00";
          //     hout = ++hout;
          //     break;

          //   default:
          //     minDate = "00";
          // }
          if (hout < 10) {
            hout = "0" + hout;
          }
          // console.log(minDate);
          // this.istartime = `${hout}:${minDate}`; // 整数时间段开始考试
          this.istartime = `${hout}:${mint < 10 ? "0" + mint : mint}`;
          // console.log(minDate , this.istartime );
        } else {
          this.istartime = "08:30";
        }
      }
    },
    // 开始时间 设置结束时间
    starselect(val) {
      if (val) {
        this.ruleForm.endTime = "";
        let st = val.split(":")[0]++;
        let st2 = val.split(":")[1]++;
        this.isEndTime = 4 + st + ":" + (1 + st2);
      }
    },
    // 考试结束时间
    endselect(val) {
      if (val) {
        if (
          this.ruleForm.region2 &&
          this.ruleForm.startTime &&
          this.ruleForm.endTime &&
          this.ruleForm.date1
        ) {
          this.timeJudeg();
        }
      }
    },
    // 查看考试时间
    seeTime() {
      if (this.ruleForm.region2[1]) {
        queryTime({ roomId: this.ruleForm.region2[1] }).then((res) => {
          this.timeTable = res.data;
          this.timeVisible = true;
        });
      } else {
        this.$message.warning("请选择一个教室");
        this.$refs.exroom.$el.click();
      }
    },
    // 获取班级列表
    elect(val) {
      console.log(val);
    },

    // 根据考试地点获取机器编号
    examination(id) {
      // console.log(id);
      quSelecteq({ roomCode: id[1] })
        .then((res) => {
          console.log(res);
          this.examAmount = res.data.length;
          this.subArrayNum = res.data;
        })
        .catch((err) => {
          console.log(err);
        });
      if (
        this.ruleForm.region2 &&
        this.ruleForm.startTime &&
        this.ruleForm.endTime &&
        this.ruleForm.date1
      ) {
        this.timeJudeg();
      }
    },

    // 获取考试人员
    examManage(bcid) {
      examManage({
        studentBatch: bcid,
      })
        .then((res) => {
          console.log(res);
          this.ruleForm.testPers = [];
          this.origindata = res.data;
          // let datss = res.data.map((item) => {
          //   return { key: item.studentId, label: item.studentName };
          // });
          this.dataUser = res.data;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 选择考试人员
    // tode
    // handleChange(value, direction, movedKeys) {
    handleChange(value, direction, movedKeys) {
      // console.log(value);
      console.log(movedKeys);
      this.ruleForm.testPers = value;
      if (value.length > this.examAmount) {
        let ava = value.slice(0, this.examAmount);
        this.ruleForm.testPers = ava;
        this.$message.error(`当前教室只能选择${this.examAmount}考生!`);
        this.dataUser.forEach((item) => {
          item.disabled = true;
          ava.forEach((ite) => {
            if (item.studentId == ite) {
              item.disabled = false;
            }
          });
        });
      }
      if (direction == "left") {
        this.dataUser.forEach((item) => {
          item.disabled = false;
        });
      }
    },

    // 设置选择个数
    leftCheckChange(check) {
      console.log(check);
      // console.log(nocheck);
      let len = this.ruleForm.testPers.length;
      // console.log( this.ruleForm.testPers);
      // this.dataUser 穿梭框数组
      if (check.length + len >= this.examAmount) {
        this.$message.warning(`当前教室只能选择${this.examAmount}考生!`);
        this.dataUser.forEach((item) => {
          item.disabled = true;
          check.forEach((ite) => {
            if (item.studentId == ite) {
              item.disabled = false;
            }
          });
        });
      } else {
        this.dataUser.forEach((item) => {
          item.disabled = false;
        });
      }
    },
    addTest(a) {
      switch (a) {
        case "isAddTest":
          if (this.isAddTest) {
            this.isUers = false;
          }
          this.isAddTest = !this.isAddTest;
          break;
        case "isUers":
          this.isUers = !this.isUers;
          break;
        default:
          console.log(a);
      }
    },
    // 选择分配考试
    electEaxmine() {
      if (!this.ruleForm.region2) {
        this.$message.warning("请先选择考试地点!");
        this.$refs.exroom.$el.click();
      } else if (!this.ruleForm.region3) {
        this.$message.warning("请先选择考试考试批次!");
        this.$refs.exambatch.$el.click();
      } else {
        this.isUers = true;
      }
    },

    // 考位分配
    // allcation() {
    //   this.twoarrymethod();
    //   this.isAssign = !this.isAssign;
    // },
    selectchange(e) {
      let toggle = e.currentTarget.parentNode.children[3].style.display;
      if (toggle == "none") {
        e.currentTarget.parentNode.children[3].style.display = "block";
      } else {
        e.currentTarget.parentNode.children[3].style.display = "none";
      }
    },
    sss(event) {
      console.log(event.target.parentNode.parentNode);
      let val = event.target.value;
      this.lista2 = this.lista2.filter((item) => item.studentId != val);
      let nn = event.target.selectedIndex;
      let tuser = event.target.options[nn].innerText;
      console.log(tuser);
      //  console.log(event.currentTarget.parentNode.firstChild);
      // this.acalist.forEach((item) => {
      //   console.log(item);
      // });
      event.currentTarget.parentNode.firstChild.innerText = tuser;
      event.currentTarget.style.display = "none";
    },
    dellist(e) {
      let vaid = e.currentTarget.parentNode.getAttribute("value");
      e.currentTarget.parentNode.children[0].firstChild.remove(); //删除td 一个元素的第一个文本节点
      var aaw = this.acalist.filter((item) => item.studentId == vaid);
      this.lista2.push(aaw[0]); // 获得删除的数组
      // const newArr = this.acalist.filter((items) => {
      //   if (!this.lista.includes(items)) return items;
      // });
      // this.lista2 = newArr;
    },
    determin() {
      this.isAssign = false;
    },
  },
};
</script>
<style lang="scss" scoped>
.tjks {
  color: white;
  font-size: 22px;
  float: left;
  cursor: pointer;
  border: 1px solid #006560;
  background: #006560;
  border-radius: 9px;
  padding: 5px 10px;
}
.cktime {
  background: #ebebeb;
  border: none;
  margin-top: 10px;
  color: #1db3b3;
}
.kstable::before {
  content: "";
  display: block;
  clear: both;
}

.kstable {
  text-align: left;
  padding: 15px 10px 5px;
  border-bottom: 3px solid #109494;
}
.demo-ruleForm {
  h3 {
    padding: 10px;
    background: #006568;
    color: white;
  }

  .tjks {
    font-size: 14px;
    height: 40px;
    line-height: 40px;
    padding: 0 15px;
  }
  .el-date-editor.el-input,
  .el-date-editor.el-input__inner {
    width: auto;
  }
}

.users {
  width: 655px;
  position: fixed;
  top: 50%;
  left: 56%;
  background: #f2f2f2;
  transform: translate(-50%, -50%);
  box-shadow: 0 0 15px #aaa;
  z-index: 999;
  .el-button + .el-button {
    margin-left: 0;
    display: block;
  }
}
i.colr {
  color: red;
}
i.coll {
  color: #67c23a;
}
i.colh {
  color: #dfdfdf;
}
.assign {
  padding: 10px;
  h1 {
    padding: 8px 0;
  }
  table {
    border-collapse: collapse;
    background: #fff;
    border: 1px solid #006560;
    border-bottom: none;
    margin-bottom: 10px;
    tr {
      position: relative;
      border-bottom: 1px solid #006560;
    }

    th,
    td {
      line-height: 32px;
      font-size: 14px;
      border-right: 1px solid #006560;
    }
    tr::after {
      content: "";
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      width: 100%;
      height: 1px;
      background: #d4d4d4;
    }

    .born,
    td:last-child {
      border: none;
    }
  }
  button {
    background: #006568;
    color: white;
    border: #006560;
    border-radius: 5px;
    padding: 5px 10px;
    font-size: 16px;
  }
  button:last-child {
    margin-left: 18px;
  }
}
.el-cascader {
  width: 100%;
}

.xylist {
  cursor: pointer;
  position: relative;
  span.del {
    width: 18px;
    height: 18px;
    border-radius: 50%;
    display: block;
    float: right;
    color: white;
    background: #006560;
    font-size: 12px;
    line-height: 18px;
    margin: 7px 25px 0 0;
  }
  span.sele {
    display: block;
    float: right;
    transform: rotate(90deg) translateY(10px);
  }
  select {
    position: absolute;
    left: 100%;
    z-index: 1333;
    top: 0;
    height: 32px;
    width: 100px;
    option {
      height: 30px;
      line-height: 30px;
    }
  }
}
</style>
